<template>
  <div class="map">
    <!--
      <el-autocomplete
      v-model="search"
      class="search"
      :fetch-suggestions="onSearch"
      :trigger-on-focus="false"
      prefix-icon="el-icon-location-information"
      placeholder="请输入地址关键字"
      @select="onSelect"
      >
      <template #default="{ item }">
      <div class="search-name">{{ item.name }}</div>
      <span class="search-address" :title="item.district + item.address">{{ item.district + item.address }}</span>
      </template>
      </el-autocomplete>
    -->
    <div :id="amap" :style="`height:${height}%;`" />
  </div>
</template>

<script>
import { isArray } from "xe-utils";
import { AMAP_APP_KEY } from "@/config";

export default {
  name: "AmapMarker",
  props: {
    v: {
      type: String,
      default: "1.4.15",
    },
    isDetail: {
      type: Boolean,
      default: false,
    },
    appkey: {
      type: String,
      default: AMAP_APP_KEY,
    },
    height: {
      type: Number,
      default: 100,
    },
    lnglat: {
      type: Array,
      default: () => {
        return [114.304465, 30.593547];
      },
    },
    searchOption: {
      type: Object,
      default: () => {
        return {
          city: "武汉",
          citylimit: true,
        };
      },
    },
    mpProjectStatus: [String, Number],
  },
  data() {
    return {
      amap: `amap${Math.random().toFixed(8)}`,
      search: "",
      map: "",
      marker: "",
      autoComplete: "",
    };
  },
  mounted() {
    if (typeof AMap === "undefined") {
      const script = document.createElement("script");
      script.charset = "utf-8";
      script.src = `https://webapi.amap.com/maps?v=${this.v}&key=${this.appkey}&plugin=AMap.Autocomplete`;
      document.head.appendChild(script);
      script.onload = () => {
        this.init();
      };
    } else {
      this.$nextTick(() => {
        this.init();
      });
    }
  },
  methods: {
    init() {
      this.map = new AMap.Map(this.amap, {
        center: this.lnglat,
        zoom: 17,
      });
      const mpProjectStatusObj = {
        1: require("@/assets/images/icon_marker1.png"),
        2: require("@/assets/images/icon_marker2.png"),
        3: require("@/assets/images/icon_marker3.png"),
        4: require("@/assets/images/icon_marker4.png"),
      };
      // 以 icon URL 的形式创建一个途经点
      const viaMarker = new AMap.Marker({
        position: new AMap.LngLat(this.lnglat[0], this.lnglat[1]),
        // 将一张图片的地址设置为 icon
        icon: mpProjectStatusObj[this.mpProjectStatus],
        anchor: "bottom-center",
        // 设置了 icon 以后，设置 icon 的偏移量，以 icon 的 [bottom center] 为原点
        offset: new AMap.Pixel(0, 0),
      });
      // 将 markers 添加到地图
      this.map.add([viaMarker]);
      //临时增加折线
      this.addPolyline();
      AMap.event.addListener(this.map, "complete", () => {
        AMap.plugin("AMap.ToolBar", () => {
          const toolbar = new AMap.ToolBar();
          this.map.addControl(toolbar);
        });
        this.marker = new AMap.Marker({
          draggable: this.isDetail ? false : true,
          cursor: "move",
        });
        this.marker.on("dragging", (e) => {
          this.marker.setPosition(e.lnglat);
        });
        this.marker.on("dragend", (e) => {
          this.$emit("update:lnglat", [e.lnglat.lng, e.lnglat.lat]);
        });
        this.autoComplete = new AMap.Autocomplete(this.searchOption);
        if (!this.isDetail) {
          this.map.on("click", (e) => {
            this.addMarket(e.lnglat.getLng(), e.lnglat.getLat());
          });
        }
        if (this.lnglat.length === 2) {
          this.addMarket(this.lnglat[0], this.lnglat[1], true);
        }
        //临时增加折线
        this.addPolyline();
      });
    },
    addPolyline() {
      const path = [
        new AMap.LngLat(114.201102, 30.572632),
        new AMap.LngLat(114.201219, 30.57286),
        new AMap.LngLat(114.200821, 30.572086),
        new AMap.LngLat(114.200952, 30.572324),
        new AMap.LngLat(114.20103, 30.57247),
        new AMap.LngLat(114.20103, 30.57247),
        new AMap.LngLat(114.201102, 30.572632),
        new AMap.LngLat(114.201219, 30.57286),
        new AMap.LngLat(114.201427, 30.573335),
        new AMap.LngLat(114.200671, 30.571795),
        new AMap.LngLat(114.200166, 30.570561),
        new AMap.LngLat(114.200671, 30.571795),
        new AMap.LngLat(114.200821, 30.572086),
      ];
      const polyline = new AMap.Polyline({
        path,
        borderWeight: 10, // 线条宽度，默认为 1
        strokeColor: "#3190FF", // 线条颜色
        // lineJoin: 'round' // 折线拐点连接处样式
      });
      this.map.add(polyline);
    },
    addMarket(lng, lat, init) {
      this.map.remove(this.marker);
      this.marker.setPosition([lng, lat]);
      // this.map.add(this.marker);隐藏标记点

      !init && this.map.setFitView();
      this.$emit("update:lnglat", [lng, lat]);
    },
    onSearch(queryString, cb) {
      if (queryString.trim()) {
        this.autoComplete.search(queryString, (status, result) => {
          if (isArray(result.tips)) {
            cb(result.tips);
          }
        });
      }
    },
    onSelect(item) {
      this.search = item.name;
      item.location ? this.addMarket(item.location.lng, item.location.lat) : this.map.setCity(item.adcode);
    },
  },
};
</script>

<style lang="scss" scoped>
.search-name {
  padding-top: 10px;
  line-height: normal;

  @include text-overflow;
}

.search-address {
  font-size: 12px;
  line-height: normal;
  color: #b4b4b4;
}

.map {
  position: relative;
  height: 100%;

  .search {
    position: absolute;
    top: 15px;
    left: 72px;
    z-index: 1;

    ::v-deep .el-input input {
      box-shadow: 0 0 5px #999;
    }
  }
}
</style>
